package com.sun.showcase.biz.basic.service.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Caching;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sun.showcase.biz.basic.dao.UserInfoDao;
import com.sun.showcase.biz.basic.service.UserGroupService;
import com.sun.showcase.biz.basic.service.UserInfoService;
import com.sun.showcase.biz.basic.service.UserResourceService;
import com.sun.showcase.client.domain.basic.UserInfo;
import com.sun.showcase.client.query.basic.UserGroupQuery;
import com.sun.showcase.client.query.basic.UserInfoQuery;
import com.sun.showcase.client.query.basic.UserResourceQuery;
import com.sun.showcase.pojo.DataGrid;
import com.sun.showcase.pojo.Pager;
import com.sun.showcase.utils.ExecuteResult;
import com.sun.showcase.utils.LoginContextHolder;
import com.sun.showcase.utils.StringConstant;
@Service("userInfoService")
@Transactional
public class UserInfoServiceImpl implements UserInfoService{
	@Autowired
	private UserInfoDao userInfoDao;
	
	@Autowired
	private UserGroupService userGroupService;
	
	@Autowired
	private UserResourceService userResourceService;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	
	public DataGrid datagrid(UserInfoQuery userInfoQuery) {
		DataGrid j = new DataGrid();
		Pager<UserInfo> pager  = find(userInfoQuery);
		j.setRows(getQuerysFromEntitys(pager.getRecords()));
		j.setTotal(pager.getTotalRecords());
		return j;
	}

	private List<UserInfoQuery> getQuerysFromEntitys(List<UserInfo> userInfos) {
		List<UserInfoQuery> userInfoQuerys = new ArrayList<UserInfoQuery>();
		if (userInfos != null && userInfos.size() > 0) {
			for (UserInfo tb : userInfos) {
				UserInfoQuery b = new UserInfoQuery();
				BeanUtils.copyProperties(tb, b);
				userInfoQuerys.add(b);
			}
		}
		return userInfoQuerys;
	}

	private Pager<UserInfo> find(UserInfoQuery userInfoQuery) {
		Page<UserInfo> page = PageHelper.startPage(userInfoQuery.getPage().intValue(), userInfoQuery.getRows().intValue());
		
		List<UserInfo> list = userInfoDao.findList(userInfoQuery);
		Pager<UserInfo> pager = new Pager<UserInfo>();
		pager.setRecords(list);
		pager.setTotalRecords(page.getTotal());
		return pager;
		
	}

	public UserInfo add(UserInfoQuery userInfoQuery) {
		
		UserInfo t = new UserInfo();
		BeanUtils.copyProperties(userInfoQuery, t);
		t.setCreateBy(LoginContextHolder.get().getUserId());
		t.setCreateByName(LoginContextHolder.get().getUserId());
		t.setCreateDate(new Date());
		t.setActiveFlag(StringConstant.ONE);
		//t.setPassword(DigestUtils.md5DigestAsHex(userInfoQuery.getPassword().getBytes()));
		t.setPassword(passwordEncoder.encode(userInfoQuery.getPassword()));
		userInfoDao.save(t);
		userInfoQuery.setId(t.getId());
		//添加个人资源
		if(StringUtils.isNotBlank(userInfoQuery.getResourceIds())){
			
			String[] resources = userInfoQuery.getResourceIds().split(",");			
			UserResourceQuery userResourceQuery = new UserResourceQuery();			
			userResourceQuery.setUserId(userInfoQuery.getId());
			
			for(int i=0;i<resources.length;i++){
				userResourceQuery.setResourceId(resources[i]);
				userResourceService.add(userResourceQuery);
			}
		}
		
		//添加组
		if(StringUtils.isNotBlank(userInfoQuery.getGroupInfoIds())){
			String[] groupInfos = userInfoQuery.getGroupInfoIds().split(",");
			UserGroupQuery userGroupQuery = new UserGroupQuery();
			userGroupQuery.setUserId(userInfoQuery.getId());
			
			for(int i=0;i<groupInfos.length;i++){
				userGroupQuery.setGroupId(groupInfos[i]);
				userGroupService.add(userGroupQuery);
			}
		}
		return t;
		
	}

	public void update(UserInfoQuery userInfoQuery) {
		
		UserInfo t = userInfoDao.getById(userInfoQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(userInfoQuery, t);
		}
	    t.setModifiedBy(LoginContextHolder.get().getUserId());
	    t.setModifiedByName(LoginContextHolder.get().getUserName());
	    t.setModifiedDate(new Date());
	    userInfoDao.update(t);
	    //添加个人资源
	    userResourceService.delete(userInfoQuery.getId());
	    
  		if(StringUtils.isNotBlank(userInfoQuery.getResourceIds())){
  			
  			String[] resources = userInfoQuery.getResourceIds().split(",");
  			UserResourceQuery userResourceQuery = new UserResourceQuery();
  			userResourceQuery.setUserId(userInfoQuery.getId());
  			
  			for(int i=0;i<resources.length;i++){
  				userResourceQuery.setResourceId(resources[i]);
  				userResourceService.add(userResourceQuery);
  			}	
  		}
	}

	public void delete(java.lang.Long[] ids) {
		if (ids != null) {
			for(java.lang.Long id : ids){
				UserInfo t = userInfoDao.getById(String.valueOf(id));
				if (t != null) {
					userInfoDao.deleteById(String.valueOf(id));
				}
			}
		}
	}

	public UserInfo get(UserInfoQuery userInfoQuery) {
		return userInfoDao.getById(userInfoQuery.getId());
	}

	public UserInfo get(String id) {
		return userInfoDao.getById(id);
	}

	
	public List<UserInfoQuery> listAll(UserInfoQuery userInfoQuery) {
	    List<UserInfo> list = userInfoDao.findList(userInfoQuery);
		List<UserInfoQuery> listQuery =getQuerysFromEntitys(list) ;
		return listQuery;
	}

	@Override
	public ExecuteResult<UserInfo> login(UserInfoQuery userInfoQuery) {
		ExecuteResult<UserInfo> executeResult = new ExecuteResult<UserInfo>();
		//根据账号查询出用户
		UserInfo userInfo=userInfoDao.getByName(userInfoQuery.getName());
		if(userInfo==null){
			executeResult.addErrorMessage("用户不存在");
			return executeResult;
		}
		if("0".equals(userInfo.getActiveFlag())){
			executeResult.addErrorMessage("用户不存在");
			return executeResult;
		}
		if(!userInfo.getPassword().equals(DigestUtils.md5DigestAsHex(userInfoQuery.getPassword().getBytes()))){
			executeResult.addErrorMessage("密码错误");
			return executeResult;
		}
		if(!"1".equals(userInfo.getStatus())){
			executeResult.addErrorMessage("用户已禁用");
			return executeResult;
		}
		//更新用户信息
		userInfo.setLastLoginIp(userInfoQuery.getLastLoginIp());
		userInfo.setLastLoginTime(new Date());
		userInfoDao.update(userInfo);
		executeResult.setResult(userInfo);
		return executeResult;
	}

	@Override
	@Caching(evict={@CacheEvict(value="queryCache", key="'queryCache_'+#p0.id" ),@CacheEvict(value="resourceCache", key="'resourceCache_'+#p0.id" )})
	public void logout(UserInfoQuery userInfoQuery) {
		
	}

	@Override
	public void editPassword(UserInfoQuery userInfoQuery) {
		userInfoQuery.setPassword(passwordEncoder.encode(userInfoQuery.getPassword()));
		userInfoDao.editPassword(userInfoQuery);
	}

	@Override
	public UserInfo getByName(UserInfoQuery userInfoQuery) {
		return userInfoDao.getByName(userInfoQuery.getName());
	}
	@Override
	public UserInfo getByName(String name) {
		return userInfoDao.getByName(name);
	}

	@Override
	public void modify(UserInfoQuery userInfoQuery) {
		userInfoDao.modify(userInfoQuery);
	}

	@Override
	public void editEmployee(UserInfoQuery userInfoQuery) {
		
		UserInfo t = userInfoDao.getById(userInfoQuery.getId());
	    if(t != null) {
	    	BeanUtils.copyProperties(userInfoQuery, t);
		}
	    t.setModifiedBy(LoginContextHolder.get().getUserId());
	    t.setModifiedByName(LoginContextHolder.get().getUserName());
	    t.setModifiedDate(new Date());
	    userInfoDao.update(t);
  		
  		//添加组
  		UserGroupQuery delUserGroupQuery = new UserGroupQuery();
  		delUserGroupQuery.setUserId(userInfoQuery.getId());
  		userGroupService.deleteByType(delUserGroupQuery);
  		
		if(StringUtils.isNotBlank(userInfoQuery.getGroupInfoIds())){
			String[] groupInfos = userInfoQuery.getGroupInfoIds().split(",");
			UserGroupQuery userGroupQuery = new UserGroupQuery();
			userGroupQuery.setUserId(userInfoQuery.getId());
			
			for(int i=0;i<groupInfos.length;i++){
				userGroupQuery.setGroupId(groupInfos[i]);
				userGroupService.add(userGroupQuery);
			}
		}
		//添加个人资源
		 userResourceService.delete(userInfoQuery.getId());
		    
	  		if(StringUtils.isNotBlank(userInfoQuery.getResourceIds())){
	  			String[] resources = userInfoQuery.getResourceIds().split(",");
	  			UserResourceQuery userResourceQuery = new UserResourceQuery();
	  			userResourceQuery.setUserId(userInfoQuery.getId());
	  			for(int i=0;i<resources.length;i++){
	  				userResourceQuery.setResourceId(resources[i]);
	  				userResourceService.add(userResourceQuery);
	  			}	
	  		}
	}
	

}
